<template>
  <pageHeader
    title="创建车间计划"
    :breadCrumb="['生产管理', '车间计划', '创建车间计划']"
    :show-back="true"
  >
    <template #footer>
      <a-button @click="router.back()">取消</a-button>
      <a-button type="primary" @click="handleOk">保存</a-button>
    </template>

    <a-spin :loading="loading" class="cantainer">
      <a-form
        :model="planProductionData"
        ref="refForm"
        auto-label-width
        class="form"
      >
        <a-row :gutter="15">
          <a-col :span="8">
            <a-form-item label="计划编号：">
              {{ planProductionData.planCode }}
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="工单编号：">
              {{ planProductionData.workOrderCode }}
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="产品编码：">
              {{ planProductionData.materialNumber }}
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="物料名称：">
              {{ planProductionData.materialName }}
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="规格型号：">
              {{ planProductionData.materialSpec }}
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="工单数量：">
              {{ planProductionData.produceNumber }}
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="已转车间计划数量：">
              {{ isToWorkshopPlan }}
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-table stripe :pagination="false" :data="formList">
        <template #columns>
          <a-table-column
            v-for="header in herders"
            :key="header.name"
            :width="header.width || 200"
            :title="header.name"
            :data-index="header.code"
            align="center"
          >
            <template #cell="{ record }" v-if="!header.code">
              <template v-if="header.name === '所属车间'">
                <a-select
                  v-model="record.workShopId"
                  @change="
                  (id) => {
                    record.workShopName = record.workshopList.find((item:any) => id === item.id)?.name;
                  }
                "
                >
                  <a-option
                    v-for="item in record.workshopList"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.code }}-{{ item.name }}
                  </a-option>
                </a-select>
              </template>
            </template>
          </a-table-column>

          <a-table-column
            :title="
              Dayjs(new Date(planProductionData.startDate || '')).format(
                'YYYY 年 MM 月'
              )
            "
            align="left"
          >
            <a-table-column
              v-for="(item, index) in dayList"
              :key="index"
              :width="140"
              align="center"
              :title="item.toDate().getDate() + '号'"
            >
              <template #title>
                <div>{{ item.toDate().getDate() + '号' }}</div>
                <div>{{
                  ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][
                    item.day()
                  ]
                }}</div>
              </template>
              <template #cell="{ record }">
                <a-input-number
                  :min="1"
                  v-model="dateObj[record.uuid + '-' + item.valueOf()]"
                />
              </template>
            </a-table-column>
          </a-table-column>
        </template>
      </a-table>
    </a-spin>
  </pageHeader>
</template>

<script setup lang="ts">
  import { reactive, onMounted, ref, computed } from 'vue';
  import {
    EditProductBom,
    GetProductBomTree,
    GetProductBomByIds,
  } from '@/api/FactoryModeling';
  import { GetProduceOrderDetails } from '@/api/produce-management/produce-list/index';
  import type {
    TPlanWorkShop,
    TPlanWorkShopDate,
  } from '@/api/produce-management/OrderPlanning/type';
  import {
    GetAllProduct,
    AddPlanWorkShops,
    GwtPlanWorkShopPage,
  } from '@/api/produce-management/OrderPlanning/index';
  import { useRoute, useRouter } from 'vue-router';
  import { GetWorkshopPage } from '@/api/FactoryModeling';
  import { TWorkshop } from '@/api/FactoryModeling/type';
  import Dayjs from 'dayjs';
  import { Message } from '@arco-design/web-vue';
  import { uniqueId } from 'lodash';

  let route = useRoute();
  let router = useRouter();
  let loading = ref(false);
  let planProductionData = reactive<any>({});
  let formList = ref<TPlanWorkShop[]>([]);
  let dateObj = reactive<any>({});

  let dayList = computed(() => {
    let list = [];
    let getNowDate = Dayjs(
      new Date(planProductionData.startDate || '')
    ).startOf('date');
    let day = getNowDate.day();
    let startDate = day
      ? getNowDate.subtract(day, 'd')
      : getNowDate.add(day, 'd');
    for (let i = 0; i < 7; i += 1) {
      list.push(startDate.add(i + 1, 'd'));
    }
    return list;
  });

  let refForm = ref();
  let handleOk = async () => {
    if (await refForm.value.validate()) return;
    let dateSetObj: any = {};
    let isErr = false;
    for (const key in dateObj) {
      let number = dateObj[key];
      let [uuid, timeStamp] = key.split('-');
      if (!Array.isArray(dateSetObj[uuid + ''])) dateSetObj[uuid + ''] = [];
      dateSetObj[uuid + ''].push({
        date: Dayjs(Number(timeStamp)).toJSON(),
        number,
      });
    }
    let form = formList.value.map((item, index) => {
      if (!item.workShopId && !isErr) {
        isErr = true;
        Message.error('第' + (index + 1) + '条数据未选择车间');
      }
      let data = {
        ...item,
        sortIndex: index,
        emergencyLevel: planProductionData.emergencyLevel,
        data: dateSetObj[item.uuid] || [],
        weeklyPlanId: planProductionData.id,
        capacity: planProductionData.capacity,
        totalNum: dateSetObj[item.uuid]
          ? dateSetObj[item.uuid].reduce(
              (num: number, { number }: any) => num + number,
              0
            ) || 0
          : 0,
      };
      delete data.dispositionData;
      delete data.uuid;
      return data;
    });
    if (isErr) return;
    loading.value = true;
    try {
      await AddPlanWorkShops({ workPlan: form });
      router.back();
    } catch (err) {
      // //
    }
    loading.value = false;
  };
  let isToWorkshopPlan = ref(0);
  onMounted(async () => {
    loading.value = true;
    try {
      let planData = JSON.parse(
        localStorage.getItem('PlanProductionForm') + ''
      );
      Object.assign(planProductionData, planData);
      let res = await GetAllProduct({ id: planData.productId });
      formList.value =
        res.processData.map((item: any) => {
          return {
            processGroupId: item.id,
            processName: item.processName,
            workOrderId: planData.workOrderId,
            produceId: planData.productId,
            produceNumber: planData.produceNumber,
            capacity: planData.capacity,
            startDate: planData.startDate,
            workshopList:
              res.dispositionData?.reduce((arr: any[], itemData: any) => {
                if (
                  itemData.processGroupId === item.id &&
                  itemData.workShopData[0]
                ) {
                  arr.push(itemData.workShopData[0]);
                }
                return arr;
              }, []) || [],
            uuid: uniqueId(),
          };
        }) || [];
      if (formList.value.length)
        planProductionData.data.forEach(({ date, number }: any) => {
          dateObj[formList.value[0].uuid + '-' + Dayjs(date).valueOf()] =
            number;
        });
      let { content } = await GwtPlanWorkShopPage({
        page: 1,
        size: -1,
        workOrderId: planData.workOrderId,
      });
      isToWorkshopPlan.value = Array.isArray(content)
        ? content
            .filter(({ sortIndex }) => !sortIndex)
            .reduce((num: number, { totalNum }: any) => num + totalNum, 0)
        : 0;
    } catch (err) {
      //
    }
    loading.value = false;
  });

  let getRules = (name?: string) => {
    return [{ required: true, message: (name || '') + '不能为空' }];
  };
  let herders = [
    { code: 'processName', name: '工序名称', width: 200 },
    { name: '所属车间', width: 280 },
  ];
</script>

<style scoped lang="less">
  .cantainer {
    padding: 20px;
    width: 100%;
  }
  .form {
    padding-left: 100px;
    padding-right: 100px;
  }
  .tab {
    border-left: 4px rgb(var(--arcoblue-6)) solid;
    padding-left: 20px;
    margin-bottom: 30px;
    font-size: 20px;
  }

  .foot {
    padding-top: 10px;
    margin-top: 10px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
  }
</style>
